<template>
	<div class="system-role-container layout-padding">
		<div class="system-role-padding layout-padding-auto layout-padding-view">
			<div class="system-user-search">
				<el-input size="default" class="w_150 mb15 mr10" v-model="listQuery.Name" placeholder="指标名" @keydown.enter="searchForm"> </el-input>

				<el-button size="default" @click="searchForm" type="primary" class="mr10 mb15"> 查询 </el-button>
				<el-button size="default" type="success" class="mr10 mb15" @click="addRule"> 新增 </el-button>
				<el-button size="default" type="info" class="mr10 mb15" @click="resetForm"> 重置 </el-button>
			</div>
			<tableTem ref="tableRef" v-bind:="state.tableData" @pageChange="onTablePageChange">
				<el-table-column align="center" type="index" label="序号" width="60" />
				<el-table-column align="center" min-width="120" prop="absFieldName" label="指标名"></el-table-column>
				<el-table-column align="center" min-width="120" prop="absFieldDisplayName" label="显示名称"></el-table-column>
				<el-table-column align="center" prop="aggregationName" min-width="120" label="聚合条件"></el-table-column>
				<el-table-column align="center" prop="searchField" min-width="120" label="搜索字段"></el-table-column>

				<el-table-column label="操作" align="center" width="190" fixed="right">
					<template #default="scope">
						<el-button size="small" type="primary" text @click="editOption(scope.row)">编辑</el-button>
						<el-button size="small" type="primary" text @click="onRowDel(scope.row.id)">删除</el-button>
					</template>
				</el-table-column>
			</tableTem>
		</div>
		<!-- 弹窗 -->
		<el-dialog
			:title="state.isEdit ? '编辑抽象' : '新增抽象'"
			v-model="state.dialogVisible"
			:close-on-click-modal="false"
			:show-close="false"
			:close-on-press-escape="false"
			width="500px"
		>
			<el-form class="dialog-layout" ref="userForm" :rules="rules" :model="state.ruleForm" size="default" label-width="100px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
						<el-form-item label="指标名" prop="absFieldName">
							<!-- <div class="flex-c-c"> -->
							<el-input v-model="state.ruleForm.absFieldName" class="w_250 mr10" placeholder="请输入指标名" clearable></el-input>
							<!-- <el-tooltip class="item" effect="dark" content="指标显示名称，一般为中文，如'100秒内设备注册数'" placement="right-end">
									<el-icon size="25px" color="#409eff">
										<ele-QuestionFilled />
									</el-icon>
								</el-tooltip> -->
							<!-- </div> -->
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
						<el-form-item label="显示名称" prop="absFieldDisplayName">
							<el-input v-model="state.ruleForm.absFieldDisplayName" class="w_250 mr10" placeholder="请输入指标名" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
						<el-form-item label="聚合条件" prop="aggregation">
							<el-select class="w_250 mr10" v-model="state.ruleForm.aggregation" size="default">
								<el-option v-for="item in state.fieldStatus" :key="item.enumValue" :label="item.desction" :value="item.enumValue"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
						<el-form-item label="搜索字段" prop="searchFieldId">
							<el-tree-select v-model="state.ruleForm.searchFieldId" :data="state.fieldList" class="w_250">
								<template #default="{ data: { label } }"> {{ label }} </template>
							</el-tree-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
						<el-form-item label="统计字段" prop="statisticsFieldId">
							<el-tree-select clearable v-model="state.ruleForm.statisticsFieldId" :data="state.fieldList" class="w_250">
								<template #default="{ data: { label } }"> {{ label }} </template>
							</el-tree-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="时间片" prop="searchIntevalValue" required>
							<div class="flex-c-c">
								<el-input v-model="state.ruleForm.searchIntevalValue" class="w_100 mr10" placeholder="时间片" clearable></el-input>
								<el-select class="w_140 mr10" v-model="state.ruleForm.searchIntevalType" size="default">
									<el-option v-for="item in state.dataList" :key="item.enumValue" :label="item.desction" :value="item.enumValue"></el-option>
								</el-select>
								<el-tooltip
									class="item"
									effect="dark"
									content="搜索某段时间的数据，数值为正数，代表范围区间，如 3 ，再配合后面的时间单位，如 月，就表示3个月内的数据"
									placement="right-end"
								>
									<el-icon size="25px" color="#409eff">
										<ele-QuestionFilled />
									</el-icon>
								</el-tooltip>
							</div>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
						<el-form-item label="备注" prop="remark">
							<el-input v-model="state.ruleForm.remark" class="w_250 mr10" placeholder="请输入备注" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div class="dialog-btn">
				<el-button @click="onCancel" size="default">取 消</el-button>
				<el-button type="primary" @click="onSubmit(userForm)" size="default">确 认</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage, FormInstance } from 'element-plus';
import {
	RiskFieldGetPagedList,
	RiskAbstractionGetPagedList,
	RiskAbstractionDelete,
	RiskAbstractionCreate,
	RiskAbstractionUpdate,
	RiskPreGetPagedList,
} from '/@/api/model/index';
import { GetEnumberOptions } from '/@/api/common/index';
// 引入组件
const tableTem = defineAsyncComponent(() => import('/@/components/tables/index.vue'));
// 定义父组件传过来的值
const props = defineProps({
	modelId: {
		type: [Number, String],
		default: () => '',
	},
});
// 定义变量内容
const tableRef = ref();
const listQuery = reactive({
	Name: '', //名称
});
const state = reactive<any>({
	tableData: {
		data: [],
		total: 0,
		loading: true,
		param: {
			PageIndex: 1,
			PageSize: 10,
		},
	},
	fieldStatus: [], // 聚合条件
	dataList: [], // 时间类型
	fieldList: [
		{
			value: 'RiskField',
			label: '基础字段',
			children: [{}],
		},
		{
			value: 'RiskPre',
			label: '预处理字段',
			children: [{}],
		},
	], // 字段列表
	ruleForm: {
		absFieldName: '', // 抽象字段名称
		absFieldDisplayName: '', // 抽象字段显示名称
		aggregation: '', // 聚合条件
		searchFieldId: '', // 查询字段
		statisticsFieldId: '', // 统计字段
		searchIntevalType: '', // 时间类型
		searchIntevalValue: '', // 时间段具体值
		remark: '', // 备注
		id: '',
	} as any, // 新增
	dialogVisible: false, // 弹窗状态
	isEdit: false, //是否编辑
});
// 页面加载时
onMounted(() => {
	getTableData();
});

// 初始化表格数据
const getTableData = async () => {
	state.tableData.loading = true;
	try {
		const params = {
			...state.tableData.param,
			...listQuery,
			modelId: props.modelId,
		};
		Object.keys(params).forEach((key) => {
			if (!params[key]) delete params[key];
		});
		let data = await RiskAbstractionGetPagedList(params);
		state.tableData.data = data.data.items;
		state.tableData.total = data.data.totalCount;
	} finally {
		state.tableData.loading = false;
	}
};

// 新增
const addRule = () => {
	(state.ruleForm = {
		absFieldName: '', // 抽象字段名称
		absFieldDisplayName: '', // 抽象字段显示名称
		aggregation: '', // 聚合条件
		searchFieldId: '', // 查询字段
		statisticsFieldId: '', // 统计字段
		searchIntevalType: '', // 时间类型
		searchIntevalValue: '', // 时间段具体值
		remark: '', // 备注
		id: '',
	} as any), // 新增
		(state.dialogVisible = true);
	state.isEdit = false;
	GetFieldTypes();
};
// 编辑
const editOption = (item: any) => {
	GetFieldTypes();
	(state.ruleForm = {
		absFieldName: item.absFieldName, // 抽象字段名称
		absFieldDisplayName: item.absFieldDisplayName, // 抽象字段显示名称
		aggregation: item.aggregation, // 聚合条件
		searchFieldId: item.searchFieldId + '+' + item.searchFieldType, // 查询字段
		statisticsFieldId: item.statisticsFieldId ? item.statisticsFieldId + '+' + item.statisticsFieldType : '', // 统计字段
		searchIntevalType: item.searchIntevalType, // 时间类型
		searchIntevalValue: item.searchIntevalValue, // 时间段具体值
		remark: item.remark, // 备注
		id: item.id,
	} as any), // 新增
		(state.dialogVisible = true);
	state.isEdit = true;
};

// 删除账户
const onRowDel = (id: any) => {
	ElMessageBox.confirm(`此操作将永久删除抽象信息，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		await RiskAbstractionDelete([id]);
		ElMessage.success('删除成功');
		getTableData();
	});
};
// 分页改变
const onTablePageChange = (val: any) => {
	state.tableData.param.PageIndex = val.pageNum;
	state.tableData.param.PageSize = val.pageSize;
	getTableData();
};
// 搜索点击时表单回调
const searchForm = () => {
	state.tableData.param.PageIndex = 1;
	tableRef.value.pageReset();
};
// 重置
const resetForm = () => {
	listQuery.Name = '';
	searchForm();
};

// 关闭弹窗
const onCancel = () => {
	state.dialogVisible = false;
};
const requiredTime = (rule: any, value: any, callback: any) => {
	console.log(state.ruleForm.searchIntevalType);

	if (value == '' || state.ruleForm.searchIntevalType === '') {
		return callback(new Error('请输入时间'));
	}
	if (!/^[+]?(\d+(\.\d+)?)?$/.test(value)) {
		return callback(new Error('请输入数字'));
	}
	callback();
};
const rules = reactive({
	absFieldName: [{ required: true, message: '请输入抽象字段名称', trigger: ['blur', 'change'] }],
	absFieldDisplayName: [{ required: true, message: '请输入抽象字段显示名称', trigger: ['blur', 'change'] }],
	aggregation: [{ required: true, message: '请选择聚合条件', trigger: ['blur', 'change'] }],
	searchFieldId: [{ required: true, message: '请选择查询字段', trigger: ['blur', 'change'] }],
	searchIntevalValue: [{ validator: requiredTime, trigger: ['blur', 'change'] }],
});
const userForm = ref<FormInstance>();
const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate(async (valid) => {
		if (valid) {
			const params = {
				...state.ruleForm,
				modelId: props.modelId,
				searchFieldType: '', // 查询字段类型
				statisticsFieldType: '', //统计类型
			};
			if (params.searchFieldId) {
				let plusIndex = params.searchFieldId.indexOf('+');
				let beforePlus = params.searchFieldId.substring(0, plusIndex);
				let afterPlus = params.searchFieldId.substring(plusIndex + 1);
				params.searchFieldId = beforePlus;
				params.searchFieldType = afterPlus;
			} else {
				params.searchFieldId = '';
				params.searchFieldType = '';
			}
			if (params.statisticsFieldId) {
				let plusIndex = params.statisticsFieldId.indexOf('+');
				let beforePlus = params.statisticsFieldId.substring(0, plusIndex);
				let afterPlus = params.statisticsFieldId.substring(plusIndex + 1);
				params.statisticsFieldId = beforePlus;
				params.statisticsFieldType = afterPlus;
			} else {
				params.statisticsFieldId = null;
				params.statisticsFieldType = null;
			}
			if (state.isEdit) {
				await RiskAbstractionUpdate(params, state.ruleForm.id);
			} else {
				delete params.id;
				await RiskAbstractionCreate(params);
			}
			ElMessage.success(state.isEdit ? '修改成功' : '新增成功');
			onCancel();
			resetForm();
		}
	});
};
//  风控字段
const processItems = (items: any, prefix: any) => {
	return items.map((item: any) => ({
		value: `${item.id}${prefix}`,
		label: item.fieldName || item.destField,
	}));
};

const GetFieldTypes = async () => {
	try {
		const params = {
			PageIndex: 1,
			PageSize: 9999,
			modelId: props.modelId,
		};

		const [dataFile, dataRisk] = await Promise.all([RiskFieldGetPagedList(params), RiskPreGetPagedList(params)]);
		let data = await GetEnumberOptions({ enumName: 'AggregationEnum' });
		let dataTime = await GetEnumberOptions({ enumName: 'DateTypeEnum' });
		state.fieldStatus = data.data;
		state.dataList = dataTime.data;
		state.fieldList[0].children = processItems(dataFile.data.items, '+RiskField');
		state.fieldList[1].children = processItems(dataRisk.data.items, '+RiskPre');
	} catch (error) {
		console.error('Failed to fetch field types:', error);
	}
};
</script>

<style scoped lang="scss">
.system-role-container {
	.system-role-padding {
		padding: 15px;
		.el-table {
			flex: 1;
		}
	}
}
.layout-padding {
	padding: 0 15px 15px 15px !important;
	width: 100%;
}
</style>
